let app = document.querySelector('#app');

import { getUser, delToken, delUser } from '../../utils/storageUtils'

import { usersReq, delUserReq } from '../../api'

import art from './index.art';


async function pageData(num, limit = 5) {

    // axios获取用户列表
    let { data: { users, total } } = await usersReq(num, limit);
    // 获取一共有多少页
    // console.log(total);
    let pageCount = Math.ceil(total / limit);

    // 获取当前页
    let pageNow = num;

    const html = art({ username: getUser().username || null, users, pageCount, pageNow });

    app.innerHTML = html;

    // 想获取删除按钮，必须在html渲染完成之后
    delUserFn(num)

    // 退出登录事件
    logoutFn()
}

pageData(1)

// 将函数暴露到全局
global.pageData = pageData;

function delUserFn(num) {
    let trs = document.querySelectorAll('#adminTable tbody tr');

    trs.forEach(item => {
        let delbtn = item.querySelector('button');
        delbtn.onclick = async function() {

            if (!confirm('确定删除吗？')) return;
            let _id = this.dataset._id;
            let { code } = await delUserReq(_id);

            if (code === 2000) {
                pageData(num)
            }
        }
    })
}

function logoutFn() {
    // 获取退出登录按钮
    let logoutBtn = document.querySelector('.logoutBtn');
    logoutBtn.onclick = function() {
        delToken();
        delUser();
        window.location.href = '/login.html';
        // axios
    }
}